package jmu.edu.yjc.controller;

import jmu.edu.yjc.Utils.BeanCopyUtil;
import jmu.edu.yjc.domain.ResponseResult;
import jmu.edu.yjc.domain.entity.Elderly;
import jmu.edu.yjc.domain.entity.User;
import jmu.edu.yjc.domain.vo.elderly.ElderlyVo;
import jmu.edu.yjc.domain.vo.user.UserInfoVo;
import jmu.edu.yjc.domain.vo.user.UserVo;
import jmu.edu.yjc.service.ElderlyService;
import jmu.edu.yjc.service.user.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/personal/elderly")
public class ElderlyController {
    @Resource
    private ElderlyService elderlyService;
    @Resource
    private UserService userService;
    @GetMapping("/list")
    public ResponseResult getElderlyList(Integer pageNum, Integer pageSize,
                                         String name, String phoneNumber){
         return elderlyService.getElderlyList(pageNum,pageSize,name,phoneNumber);
    }
    @PostMapping
    public ResponseResult addElderly(@RequestBody Elderly elderly){
        elderlyService.save(elderly);
        return ResponseResult.okResult();
    }
    @DeleteMapping("/{id}")
    public ResponseResult delElderly(@PathVariable("id") String id){
        String[] ids = id.split(",");
        elderlyService.removeByIds(Arrays.asList(ids));
        return ResponseResult.okResult();
    }
    @PutMapping
    public ResponseResult updateElderly(@RequestBody Elderly elderly){
        elderlyService.updateById(elderly);
        return ResponseResult.okResult();
    }
    @GetMapping("/{id}")
    public ResponseResult getElderly(@PathVariable("id")Long id){
        Elderly elderly = elderlyService.getById(id);
        ElderlyVo elderlyVo = BeanCopyUtil.copyBeans(elderly, ElderlyVo.class);
        if(elderlyVo.getUserId() != null){
            User user = userService.getById(elderlyVo.getUserId());
            elderlyVo.setUser(BeanCopyUtil.copyBeans(user, UserVo.class));
        }
        return ResponseResult.okResult(elderlyVo);
    }
    @PreAuthorize("@ps.hasPermission('personal:elderly:export')")
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        elderlyService.export(response);
    }
    @PreAuthorize(("@ps.hasPermission('personal:elderly:upload')"))
    @PostMapping("/upload")
    public ResponseResult uploadExcel(@RequestPart("file") MultipartFile file){
        return elderlyService.uploadExcel(file);
    }
    @GetMapping("/total")
    public ResponseResult getTotal() {
        return ResponseResult.okResult(elderlyService.count());
    }
}
